package com.tgpms.web.cost.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tgpms.common.Result;
import com.tgpms.exception.*;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.util.Common;
import com.tgpms.util.PageInfo;
import com.tgpms.util.PageView;
import com.tgpms.util.VformBeanUtil;
import com.tgpms.web.cost.dao.EstimateHierarchyMasterMapper;
import com.tgpms.web.cost.entity.EstimateHierarchyMaster;
import com.tgpms.web.cost.service.EstimateHierarchyMasterService;
import io.netty.util.internal.StringUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author May
 * <p>
 * 概算层次代码业务接口相关实现
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
@Slf4j
public class EstimateHierarchyMasterServiceImpl implements EstimateHierarchyMasterService {

    @Autowired
	private VformInterface vformInterface;


    /**
     * 查询所有概算层次代码并做分页处理
     *
     * @param pageView 分页
     * @return null
     */
    @Override
    public Result queryAll(PageInfo pageInfo) {
    	JSONObject param = new JSONObject();
		Object selparam = pageInfo.getQueryMap().get("selparam");
		Object leftdition = pageInfo.getQueryMap().get("leftdition");
		Object condition = pageInfo.getQueryMap().get("condition");
		Object dataowner = pageInfo.getQueryMap().get("dataowner");
		if(Common.isEmpty(selparam)) {
			param.put("[SQL1]", " ");
		}else {
			param.put("[SQL1]", selparam.toString());
		}
		if(Common.isEmpty(leftdition)) {
			param.put("[SQL2]", " ");
		}else {
			param.put("[SQL2]", leftdition.toString());
		}
		if(Common.isEmpty(condition)) {
			param.put("[SQL3]", " ");
		}else {
			param.put("[SQL3]", condition.toString());
		}
		Result result = vformInterface.multiForMsQueryBySql("SCWZC017", param.toJSONString(), pageInfo.getPage(), 
				pageInfo.getSize(), "Y", "Y", dataowner.toString());
		return result;
    }

    /**
     * 增加概算层次数据
     *
     * @param estimateHierarchyMaster
     * @return
     */
    @Override
    public Map<String,String> addEstimateHierarchyMasterInfo(EstimateHierarchyMaster estimateHierarchyMaster) {
    	Map<String,String> map = new HashMap<String, String>();
        //对象转json字符串, 字段驼峰转下划线大写字段
        JSONObject json = VformBeanUtil.entityToJsonString(estimateHierarchyMaster);
        if(json==null || json.isEmpty()) {
        	map.put("code", "-2");
        	map.put("info", ExceptionExplain.ERROR_BY_PARSING.getExplain());
        	return map;
        }
        System.out.println("vform增加上送参数   "+json.toString());
        //vform同步插入
        Result result = vformInterface.insert("D3105", json);
        System.out.println("vform增加返回结果   "+result);
        if(result==null || !result.getSuccess()) {
        	map.put("code", "-3");
        	map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
        	return map;
        }
        String resData = result.getData().toString();
        JSONObject reJson = JSONObject.parseObject(resData);
        if(reJson.get("status").toString().equals("error")) {
        	map.put("code", "-4");
        	map.put("info", reJson.get("validateError").toString());
        	return map;
        }else {
        	map.put("code", "1");
			map.put("info", ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
        }
        return map;
    }

    /**
     * 根据层次代码删除对应的数据
     *
     * @param estimateHierarchyCode
     * @return
     */
    @Override
    public Map<String, String> delEstimateHierarchyMaster(String estimateHierarchyCode) {
    	Map<String,String> map = new HashMap<String, String>();
		JSONObject keyjson = new JSONObject();
		keyjson.put("ESTIMATE_HIERARCHY_CODE", estimateHierarchyCode);
		System.out.println("vform删除上送主键   "+keyjson.toString());
		//vform同步删除
		Result result = vformInterface.delete("D3105", keyjson.toJSONString());
		System.out.println("vform删除返回结果   "+result);
		if(result==null || !result.getSuccess()) {
			map.put("code", "-3");
			map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
			return map;
		}
		String resData = result.getData().toString();
		JSONObject reJson = JSONObject.parseObject(resData);
		if(reJson.get("status").toString().equals("error")) {
			map.put("code", "-4");
			map.put("info", reJson.get("validateError").toString());
			return map;
		}else {
			//查询所有子集
			result = vformInterface.find("D3105", "{\"ESTIMATE_HIERARCHY_CODE\":\""+estimateHierarchyCode+"\"}","1","1000","N","N","");
			System.out.println("vform查询返回结果为:  "+result);
			if(result==null || !result.getSuccess()) {
				map.put("code", "-3");
				map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
				return map;
			}
			if(result.getData().toString().equals("{\"message\":\"login\"}")) {
				map.put("code", "-3");
				map.put("info", ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
				return map;
			}
			if(!result.getData().toString().equals("[]")) {
				List<Map<String,String>> list = JSONArray.parseObject(result.getData().toString(), List.class);
				
				List<Object> codes = new ArrayList<Object>();
				for(Map<String,String> map1 : list){
					JSONObject json = new JSONObject();
					json.put("ESTIMATE_HIERARCHY_CODE", map1.get("ESTIMATE_HIERARCHY_CODE"));
					codes.add(json);
				}
				result = vformInterface.deleteBatch("D3105", new JSONArray(codes));
				System.out.println("vform批量删除返回结果为:  "+result);
				if(result==null || !result.getSuccess()) {
					map.put("code", "-3");
					map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
					return map;
				}
			}
			map.put("code", "1");
			map.put("info", ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
		}
        return map;
    }

    /**
     * 查询菜单
     *
     * @param estimateHierarchyCode 概算ID
     * @param levelNo 层次
     * @param parentCode 父级
     * @return null
     */
    @SuppressWarnings("unchecked")
	@Override
    public List<Map<String,Object>> findKeyByMenu(PageInfo pageInfo) {
    	List<Map<String,Object>> keyByMenu = new ArrayList<Map<String,Object>>();
    	JSONObject param = new JSONObject();
		Object selparam = pageInfo.getQueryMap().get("selparam");
		Object condition = pageInfo.getQueryMap().get("condition");
		Object dataowner = pageInfo.getQueryMap().get("dataowner");
		if(Common.isEmpty(selparam)) {
			param.put("[SQL1]", " ");
		}else {
			param.put("[SQL1]", selparam.toString());
		}
		if(Common.isEmpty(condition)) {
			param.put("[SQL2]", " ");
		}else {
			param.put("[SQL2]", condition.toString());
		}
		Result result = vformInterface.multiForMsQueryBySql("SCWZC018", param.toJSONString(), pageInfo.getPage(), 
				pageInfo.getSize(), "Y", "Y", dataowner.toString());
		if(result.getSuccess()) {
			Map resMap = JSONObject.parseObject(result.getData().toString());
			if(Integer.parseInt(resMap.get("total").toString())<=0) {
				return keyByMenu;
			}
			keyByMenu = JSONArray.parseObject(resMap.get("rows").toString(), List.class);
			for (Map<String, Object> byMenu : keyByMenu) {
	            String isLeaf = (String) byMenu.get("ISLEAF");
	            if ("true".equals(isLeaf)) {
	                byMenu.remove("ISLEAF");
	                byMenu.put("ISLEAF", true);
					byMenu.put("hasChildren", false);
	            } else if ("false".equals(isLeaf)) {
	                byMenu.remove("ISLEAF");
	                byMenu.put("ISLEAF", false);
					byMenu.put("hasChildren", true);
	            }
	        }
			log.info("查询概算层级树形结果为："+keyByMenu);
		}
		return keyByMenu;
    }

    /**
     * 更新概算层次代码相关数据
     *
     * @return
     */
	@Override
	public Map<String, String> updateEstimateHierarchyMasterInfo(EstimateHierarchyMaster estimateHierarchyMaster) {
		Map<String,String> map = new HashMap<String, String>();
		JSONObject keyjson = new JSONObject();
		keyjson.put("ESTIMATE_HIERARCHY_CODE", estimateHierarchyMaster.getEstimateHierarchyCode());
		JSONObject pajson = new JSONObject();
		pajson = VformBeanUtil.entityToJsonStringByUpdate(estimateHierarchyMaster);
		pajson.remove("ESTIMATE_HIERARCHY_CODE");

		System.out.println("vform更新上送主键   "+keyjson.toString());
		System.out.println("vform更新上送参数   "+pajson.toString());
		//vform同步更新
		Result result = vformInterface.update("D3105", keyjson.toString(),pajson.toString(),"Y","Y",estimateHierarchyMaster.getDataOwner());
		System.out.println("vform更新返回结果   "+result);
		if(result==null || !result.getSuccess()) {
			map.put("code", "-3");
			map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
			return map;
		}
		String resData = result.getData().toString();
		JSONObject reJson = JSONObject.parseObject(resData);
		if(reJson.get("status").toString().equals("error")) {
			map.put("code", "-4");
			map.put("info", reJson.get("validateError").toString());
			return map;
		}else {
			map.put("code", "1");
			map.put("info", ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
		}
		return map;
	}
}
